const Service = require("egg").Service;


const getSql = (table)=>{
    let sql = ''
    if(table.startsWith('t_realdata')) {
        sql = ` select a.*, b.ss_AllWarnNum, b.ss_WarnClass1Num, b.ss_WarnClass2Num, b.ss_WarnClass3Num, b.ss_WarnClass4Num 
        from ${table} a 
        left join t_dev_state b on a.pdi_index = b.pdi_index
        where a.pdi_index = :pdi `
        return sql
    } 
    sql = ` select * from ${table} where pdi_index = :pdi `
    return sql
}

class DataService extends Service {


    /**
     * 获取历史表和实时数据
     */
    async getTableData(table, pdi, time=null) {

       if(!pdi) return []

        const { ctx, app } = this

        if(!table) {
            ctx.throw(422, ctx.__('The data does not exist'))
        }

        let sql = getSql(table)

        if(time) {
            sql += ` and hd_datetime >= :time`
        }

        return await app.model.query(sql, { 
            type: app.Sequelize.QueryTypes.SELECT,
            raw: true,
            replacements: { 
                pdi,
                table,
                time 
            }, 
        })
    }

    /**
     * 获取设备信息
     */
    async getDeviceInfo(pdi) {
        const { app } = this
        return await app.model.TPrideviceinfo.findOne({
            where: { pdi_index: pdi },
            include: {
                model: app.model.TDevicetype,
                as: 'devicetype',
                attributes: ['dt_typeid', 'dt_rtdata_table', 'dt_hisdata_table']
            }
        })
    }

    /**
     * 每日告警历史数据
     */
    async getAlarmHistory(pdi, startTime) {
        const { app, ctx } = this
        ctx.logger.info(startTime, 'alarm start.....')
        const { Op } = app.Sequelize
        return await app.model.THistorywarn.findAll({
            where: { 
                pdi_index: pdi,
                Rs_status: 1,
                rs_updatetime: {
                    [Op.gte]: startTime
                }
             },
        })
    }

    /**
     * 每日告警实时数据
     */
    async getAlarmReal(pdi, typeid=null) {
        const { app, ctx } = this
        ctx.logger.info('alarm real.....')

        let where = {}

        if(pdi) {
            where['pdi_index'] = pdi
        }

        if(typeid) {
            where['pdi_type'] = typeid
        }

        return await app.model.TPhpwarn.findAll({
            where: where,
            attributes: ['pdi_index', 'pdi_name', 'pdi_type', 'pdi_warnname', 'pdi_warnlevel', 'pdi_updatetime']
        })
    }

    /**
     * 根据分类获取设备信息
     */
    async getTypeDevice(typeId, cid=null) {
        const { app } = this
        let where = {}
        if(typeId) {
            where['dpt_id'] = typeId;
        }

        if(cid) {
            where['Co_ID'] = cid;
        }
        return await app.model.TPrideviceinfo.findAll({
            where: where,
            attributes: ['pdi_index', 'pdi_name', 'dpt_id']
        })
    }

    /**
     * 获取设备告警数量
     */
    async getDeviceAlarmCount(pdi) {
        const { app } = this
        if(Array.isArray(pdi)) {
            return await app.model.TDevState.findOne({
                where: { pdi_index: pdi },
                attributes: [
                    app.Sequelize.fn('sum', app.Sequelize.col('ss_WarnClass1Num')), 
                    app.Sequelize.fn('sum', app.Sequelize.col('ss_WarnClass2Num')), 
                    app.Sequelize.fn('sum', app.Sequelize.col('ss_WarnClass3Num')), 
                    app.Sequelize.fn('sum', app.Sequelize.col('ss_WarnClass4Num'))
                ]
            })
        }

        return await app.model.TDevState.findOne({
            where: { pdi_index: pdi },
        })
    }




    /**
     * 根据分类获取所有设备实时信息
     */
    async getTypeRealData(typeid, table) {
        const { app } = this
        const sql = `
            select a.pdi_name, a.SubType, b.* from ${table} b 
            left join t_prideviceinfo a on a.pdi_index = b.pdi_index
            where dpt_id = :typeid
        `

        return await app.model.query(sql, { 
            type: app.Sequelize.QueryTypes.SELECT,
            raw: true,
            replacements: { 
                typeid,
                table
            }, 
        })
    }


    /**
     * 统计每日告警次数
     */
    async getDayAlarmCount(pdi, startTime) {
        if(!pdi) return []

        const { app } = this

        const groupField = app.Sequelize.literal("date_format(rs_updatetime, '%Y-%m-%d %H') as hours")

        return await app.model.THistorywarn.findAll({
            where: { 
                pdi_index: pdi,
                Rs_status: 1,
                rs_updatetime: {
                    [app.Sequelize.Op.gte]: startTime
                }
             },
             attributes: [ 
                groupField,
                app.Sequelize.literal("count(hw_index) AS num"),
            ],
            group: [
                'hours'
            ]
        })

    }

    //设备分类

    async deviceTypes() {

        const { app } = this

        const types = await  this.ctx.model.TDevicetype.findAll({

            where: {
                dt_typeid: {
                    [app.Sequelize.Op.gt]: 0
                }
            },
            attributes: [
                'dt_typeid', 'dt_typememo'
            ],
            include: {
                model: app.model.TSubdevicetype,
                as: 'subtype',
                attributes: ['ts_Maintypeid', 'ts_TypeMo', 'ts_typeid']
            }
        })

        return types;
    }
    
}

module.exports = DataService